<?php

class Nuo_Session_Database extends Nuo_Session_Abstract
{


	/**
	 * Read session data
	 *
	 * @param string $id
	 * @return string
	 */
	public function read($id)
	{

		$db = Database::instance();

		$table = 'nuo_session';

		$item = $db -> fetchRow("select * from nuo_session where id = '{$id}'");

		if (FALSE == $item)
		{
			return '';

		}

		$this -> _exsists = TRUE;

		if ($item['expired_at'] < time())
		{
			return '';
		}

		/**
		 * set lifetime to use later
		 */
		$this -> setLifetime($item['lifetime']);

		return $item['data'];
	}

	/**
	 * Write session data
	 *
	 * @param string $id
	 * @param string $data
	 * @return boolean
	 */
	public function write($id, $data)
	{

		/**
		 * Database instance
		 * @param Database_Adapter
		 */
		$db = Database::instance();

		/**
		 * @var string
		 */
		$table = Nuo::getT('session');

		/**
		 * current time
		 */
		$time = time();

		/**
		 * @var int
		 */
		$lifetime = $this -> getLifetime();

		/**
		 * check that session exsists!
		 */
		if ($this -> _exsists)
		{
			$db -> update($table, array(
				'data' => $data,
				'lifetime' => $lifetime,
				'modified_at' => $time,
				'expired_at' => $time + $lifetime,
			), "id='{$id}'");
		}
		else
		{
			$db -> insert($table, array(
				'id' => $id,
				'lifetime' => $lifetime,
				'modified_at' => $time,
				'expired_at' => $time + $lifetime,
				'data' => $data,
			));
		}
		return TRUE;
	}

	/**
	 * Destroy session
	 *
	 * @param string $id
	 * @return boolean
	 */
	public function destroy($id)
	{
		/**
		 * Database instance
		 * @param Database_Adapter
		 */
		$db = Database::instance();

		/**
		 * @var string
		 */
		$table = Nuo::getT('session');

		$db -> delete($table, "id='{$id}'");

		return TRUE;
	}

	/**
	 * Garbage Collection
	 *
	 * @param int $maxlifetime
	 * @return TRUE
	 */
	public function gc($maxlifetime)
	{
		/**
		 * Database instance
		 * @param Database_Adapter
		 */
		$db = Database::instance();

		/**
		 * @var string
		 */
		$table = Nuo::getT('session');

		$db -> delete($table, "exipired_at< " . time());

		return TRUE;
	}

}
